package com.example.erat.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.erat.common.BusinessException;
import com.example.erat.common.ExcelUtils;
import com.example.erat.entity.Student;
import com.example.erat.entity.Submission;
import com.example.erat.mapper.StudentMapper;
import com.example.erat.mapper.SubmissionMapper;
import com.example.erat.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private SubmissionMapper submissionMapper;

    @Override
    public List<Student> getStudentsByClass(String className) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getClassName, className);
        return this.list(wrapper);
    }

    @Override
    public void importStudents(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException("导入文件不能为空");
        }
         //使用ExcelUtils解析Excel文件
        List<Student> studentList = ExcelUtils.importExcel(file, 1, 1, Student.class);
         //批量保存学生数据
        this.saveBatch(studentList);


    }

    @Override
    public Integer getSubmissionCount(String studentId, String courseId) {
        // 查询条件：学生ID + 课程ID
        Map<String, Object> params = new HashMap<>();
        params.put("student_id", studentId);
        params.put("course_id", courseId);

        // 使用自定义SQL查询提交次数
        return submissionMapper.selectSubmissionCount(params);
    }

    @Override
    public Double getAverageScore(String studentId, String courseId) {
        // 查询条件：学生ID + 课程ID
        Map<String, Object> params = new HashMap<>();
        params.put("student_id", studentId);
        params.put("course_id", courseId);

        // 使用自定义SQL查询平均分
        return submissionMapper.selectAverageScore(params);
    }
}
